const TestAdminDetailModel = require('../../../models/testbank/testadminbankdetail/testadminbankdetail')

//获取详情页面
class TestAnswerController {
  async postTestAnswer(ctx) {
    try {



      // 获取 iid
      console.log(ctx.request.body, '这是前端传来的数据')



      const {  iid, answer } = ctx.request.body.detailparams
      console.log(ctx.request.body.detailparams.iid, '这是iid名字')

      console.log(ctx.request.body.detailparams.answer['0'], '这是前端传来的答案的分类名字')

      // 打开这个会报错
      // if (!nid) {
      //   ctx.status = 400
      //   ctx.body = { error: 'Missing required field: label' }
      //   return
      // }

      // const answerTestAdminDetailData = await TestAdminDetailModel.find({ iid })

      const result = await TestAdminDetailModel.aggregate([
        { $unwind: "$questions" },          // 展开 questions 数组
        { $match: { "questions.iid": iid } }, // 匹配题目 ID
        { $project: {
          _id: 0,
          questionData: "$questions"
        }}
      ]);

      const answerTestAdminDetailData = result[0]?.questionData;

      console.log(answerTestAdminDetailData, '聚合管道查询的答案数据')
      // console.log(answerTestAdminDetailData.correctAnswer,'这是数据库储存的正确答案')
      // console.log(answer['0'] == answerTestAdminDetailData.correctAnswer,'前后端答案匹配')
      const correctAnswer= answerTestAdminDetailData.correctAnswer


      // 判断答案
      const isCorrect = answer['0'] == answerTestAdminDetailData.correctAnswer
      console.log(isCorrect, '答案的对错')

      ctx.status = 200
      ctx.body = {
        success: true,
        data: {
          answerTestAdminDetailData,
          iid,
          correctAnswer,
          isCorrect
        },

      }
    } catch (err) {
      console.error(err) // 打印完整错误信息
      ctx.status = 500
      ctx.body = { error: 'Failed to save data', details: err.message }
    }
  }

}

//判断答案的对错

module.exports = new TestAnswerController()
